package com.xk._02算法篇._01sort;

import com.xk.tools.Asserts;

/**
 * @description:
 * @author: xu
 * @date: 2022/10/2 0:09
 */
public class BinarySearch {
    public static int indexOf(Integer[] array, int v) {
        if (array == null || array.length == 0) return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (v > array[mid]) {
                begin = mid + 1;
            } else if (v < array[mid]) {
                end = mid;
            } else {
                return mid;
            }
        }
        return -1;
    }

    /**
     * 查找v在有序数组中的待插入位置
     * @param array
     * @param v
     * @return
     */
    public static int search(Integer[] array, int v) {
        if (array == null || array.length == 0) return -1;
        int begin = 0;
        int end = array.length;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (v >= array[mid]) {
                begin = mid + 1;
            } else {
                end = mid;
            }
        }
        return begin;
    }

    public static void main(String[] args) {
        Integer[] array = { 2, 4, 6, 7, 11, 15, 22, 26 };
        Asserts.test(search(array, 5) == 2);
        Asserts.test(search(array, 1) == 0);
        Asserts.test(search(array, 15) == 6);
        Asserts.test(search(array, 33) == 8);
    }
}
